package com.scs.application.core.mvc.validator;

import com.scs.application.core.utils.StringUtils;
import com.scs.application.modules.upgrade.db.annotation.EntityFieldAnnotation;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
/**
 * @Description： 实体验证器
 */
public class EntityValidator implements ConstraintValidator<EntityFieldAnnotation, Object> {

    private EntityFieldAnnotation constraintAnnotation;

    @Override
    public void initialize(EntityFieldAnnotation constraintAnnotation) {
        this.constraintAnnotation = constraintAnnotation;
    }


    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        context.disableDefaultConstraintViolation();
        boolean notNull = constraintAnnotation.not_null();
        int length = Integer.parseInt(StringUtils.defaultIfBlank(constraintAnnotation.length(), "50"));

        String text = constraintAnnotation.text();

        if (notNull && value == null) {
            context.buildConstraintViolationWithTemplate(String.format("%s 不能为空", text))
                    .addConstraintViolation();
            return false;
        }

        if (value instanceof String) {
            if (value == null) {
                context.buildConstraintViolationWithTemplate(String.format("%s 不能为空", text))
                        .addConstraintViolation();
                return false;
            }

            String valueString = (String) value;
            int minLength = notNull ? 1 : 0;
            if (valueString.length() < minLength || valueString.length() > length) {
                context.buildConstraintViolationWithTemplate(String.format("%s 必须介于%d~%d 之间",
                        text,minLength, length
                ))
                        .addConstraintViolation();
                return false;
            }
        }

        return true;
    }
}
